package com.itlong.cloud.commons.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.app.AppElevatorAuthDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.app.AppCloudIntercomsVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorAuthVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorInfoVO;
import com.itlong.cloud.POJO.VO.app.AppEntranceOrCloudIntercomAuthVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.commons.dao.ICloudElevatorDao;
import com.itlong.cloud.commons.dao.ICloudTalkPushCloudIntercomChangeLogDao;
import com.itlong.cloud.commons.service.ICloudTalkPushCloudIntercomChangeLogService;
import com.itlong.cloud.commons.thread.queue.process.queue.SendIotPushMessageQueue;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.property.dao.ICloudIntercomDeviceServiceDao;
import com.itlong.cloud.property.dao.IDeviceBusinessChangeLogDao;
import com.itlong.cloud.property.dao.IDeviceCloudIntercomInfoDao;
import com.itlong.cloud.property.dao.IPropertyEquipDao;
import com.itlong.cloud.property.dao.IDeviceEntranceInfoDao;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      云对讲响应硬件结果业务处理接口实现类
 * </desc>
 *
 * @createDate 2017/12/04
 */
@Service
@RefreshScope
public class CloudTalkCloudTalkPushCloudIntercomChangeLogServiceImpl implements ICloudTalkPushCloudIntercomChangeLogService {
    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkCloudTalkPushCloudIntercomChangeLogServiceImpl.class);

    @Autowired
    IDeviceBusinessChangeLogDao iDeviceBusinessChangeLogDao;

    @Autowired
    ICloudTalkPushCloudIntercomChangeLogDao iCloudTalkPushCloudIntercomChangeLogDao;

    @Autowired
    IDeviceCloudIntercomInfoDao iDeviceCloudIntercomInfoDao;

    @Autowired
    IAppDeviceService iAppDeviceService;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    @Autowired
    ICloudIntercomDeviceServiceDao iCloudIntercomDeviceServiceDao;

    @Autowired
    SendIotPushMessageQueue sendIotPushMessageQueue;

    @Autowired
    RedisService redisService;

    @Autowired
    MessageSender messageSender;

    @Autowired
    IPropertyEquipDao iPropertyEquipDao;

    private  ExecutorService  cachedThreadPool ;

    @Value("${" + PlatformConstants.H5_PAYMENT_HTML + "}")
    public String H5_PAYMENT_HTML;

    @Autowired
    ICloudElevatorDao iCloudElevatorDao;

    @Autowired
    IDeviceEntranceInfoDao iDeviceEntranceInfoDao;

    @PostConstruct
    public void init() {
        cachedThreadPool = Executors.newFixedThreadPool(100);
    }
    /**
     * <desc>
     *      任务调度执行同步业务指令至响应硬件结果表
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/04
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void timeTaskPushCloudIntercom() throws Exception {
        List<DeviceBusinessChangeLogPO> business = iDeviceBusinessChangeLogDao.getPendingBusiness(null,null);
        if(!business.isEmpty()) {
            Set<String> projectIds = new HashSet<>();
            //获取当前需要进行业务同步的所有项目
            business.forEach(po -> {
                projectIds.add(po.getProjectId());
            });
            //遍历项目id，以项目为中心
            for (String projectId : projectIds) {
                Integer fullType=null;
                //查找是否有全量更新
                if (business.stream().filter(po ->
                        po.getCommandType() == SmartCommunityEnum.PUSH_RELOGIN.getCommandType() && po.getProjectId().equals(projectId)).findFirst().isPresent()) {
                    //云对讲业务服务器地址变更 /device/login
                    fullType=SmartCommunityEnum.PUSH_RELOGIN.getCommandType();
                }
                if (business.stream().filter(po ->
                        po.getCommandType() == SmartCommunityEnum.PUSH_FULL.getCommandType() && po.getProjectId().equals(projectId)).findFirst().isPresent()) {
                    //房间全量更新 /device/pullDeviceAuthInfo
                    fullType=SmartCommunityEnum.PUSH_FULL.getCommandType();
                }
                if (fullType!=null) {
                    //更新状态为已处理
                    this.updateFull(projectId,fullType);
                    continue;
                }
            }
        }
    }


    /**
     * <desc>
     *      云对讲单个设备物理地址变更
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public synchronized void setPushDeviceOne(List<DeviceBusinessChangeLogPO> business){
        try {
            List<PushCloudIntercomChangeLogPO> devices = new ArrayList<>();
            Set<String> deviceSet=new HashSet<>();
            for(DeviceBusinessChangeLogPO bus : business){
                Map<String,Object> map=JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
                if(deviceSet.add(map.get("deviceUnique").toString())){
                    PushCloudIntercomChangeLogPO push=new PushCloudIntercomChangeLogPO();
                    push.setCommandId(LogicIdUtil.bussinessId());
                    push.setDeviceUnique(map.get("deviceUnique").toString());
                    push.setSn(map.get("sn").toString());
                    push.setCommandType(PushCloudIntercomChangeEnum.PUSH_FULL.getType());
                    push.setCommandData("/device/login");
                    push.setStatus(DataStatusEnum.DELETE.getType());
                    push.setCreateTime(new Date());
                    devices.add(push);
                }
            }
            if(!devices.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(devices);
                this.sendIotMessage(devices);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表单个设备物理地址变更执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + "："+e);
        }
    }


    /**
     * <desc>
     *      全量更新
     * </desc>
     *
     * @param projectId 项目id
     * @author Jiaqi.X
     * @createDate 2017/12/11
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void updateFull(String projectId,Integer type){
        try {
            List<PushCloudIntercomChangeLogPO> full =new ArrayList<>();
            List<DeviceCloudIntercomInfoPO> clouds = iDeviceCloudIntercomInfoDao.getCloudIntercomsByProjectId(projectId);
            for(DeviceCloudIntercomInfoPO cloud : clouds) {
                PushCloudIntercomChangeLogPO push = new PushCloudIntercomChangeLogPO();
                push.setCommandId(LogicIdUtil.bussinessId());
                push.setDeviceUnique(cloud.getDeviceUnique());
                push.setSn(cloud.getSn());
                push.setCommandType(PushCloudIntercomChangeEnum.PUSH_FULL.getType());
                if (type == SmartCommunityEnum.PUSH_RELOGIN.getCommandType()) {
                    push.setCommandData("/device/login");
                } else {
                    push.setCommandData("/device/pullDeviceAuthInfo");
                }
                push.setStatus(DataStatusEnum.DELETE.getType());
                push.setCreateTime(new Date());
                full.add(push);
            }
            if(!full.isEmpty()){
                if(!full.isEmpty()) {
                    iCloudTalkPushCloudIntercomChangeLogDao.batchSave(full);
                    this.sendIotMessage(full);
                }
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表全量更新执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + "："+e);
        }
    }


    /**
     * <desc>
     *      处理推送设备响应房间信息
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/09
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushRoom(List<DeviceBusinessChangeLogPO> business) {
        try {
            //通过项目id获取当前需要被处理的业务
            List<PushCloudIntercomChangeLogPO> rooms = new ArrayList<>();
            Map<String,Object> buildMap=new HashMap<>();
            List<Map<String, Object>> roomIds = new ArrayList<>();
            for (DeviceBusinessChangeLogPO bus : business) {
                List<Map<String,Object>> rms = JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {});
                roomIds.addAll(rms);
            }
            //查询
            if (business.size() > 0) {
                for (Map<String, Object> room : roomIds) {
                    String buildId=room.get("buildId").toString();
                    String unitId=room.get("unitId").toString();
                    //房间号去重
                    Set<String> roomSet=buildMap.get(buildId+","+unitId) != null ? (Set<String>)buildMap.get(buildId+","+unitId) : new HashSet<>();
                    roomSet.add(room.get("roomId").toString());
                    buildMap.put(buildId+","+unitId,roomSet);
                }
                //门口机
                List<PushCloudRoomInfoDeviceVO> gates = iAppDeviceDao.getGatesByRoomIds(roomIds);
                //围墙机
                List<PushCloudRoomInfoDeviceVO> walls = iAppDeviceDao.getWallsByRoomIds(roomIds);
                List<PushCloudRoomInfoDeviceVO> clouds = new ArrayList<>();
                if (!gates.isEmpty()) {
                    clouds.addAll(gates);
                }
                if (!walls.isEmpty()) {
                    clouds.addAll(walls);
                }
                Map<String,Object> sqlRooms = new HashMap<>();
                for (PushCloudRoomInfoDeviceVO cloud : clouds) {
                    PushCloudIntercomChangeLogPO ownedPush = new PushCloudIntercomChangeLogPO();
                    ownedPush.setCommandType(PushCloudIntercomChangeEnum.PUSH_ROOM.getType());
                    ownedPush.setStatus(DataStatusEnum.DELETE.getType());
                    ownedPush.setCreateTime(new Date());
                    ownedPush.setCommandId(LogicIdUtil.bussinessId());
                    ownedPush.setDeviceUnique(cloud.getDeviceUnique());
                    ownedPush.setSn(cloud.getSn());
                    List<PushRoomCommanDataVO> voList = new ArrayList<>();
                    Set<String> keySet=buildMap.keySet();
                    for(String buildAndUnit : keySet){
                        String[] bu = StringHandlerUtil.splitString(buildAndUnit);
                        String build=bu[0];
                        String unit=bu[1];
                        if((cloud.getSmartType().equals(CloudIntercomTypeEnum.GATE.getType().toString())
                                &&cloud.getBuildId().equals(build) && cloud.getUnitId().indexOf(unit) > -1)||
                                (cloud.getSmartType().equals(CloudIntercomTypeEnum.WALL.getType().toString())
                                        &&cloud.getBuildId().contains(build))){
                            Set<String> roomIdSet= (Set<String>)buildMap.get(buildAndUnit);
                            String[] roomSets=roomIdSet.toArray(new String[roomIdSet.size()]);
                            for(String rId : roomSets){
                                PushRoomCommanDataVO pushVO;
                                try {
                                    if(sqlRooms.get(rId) == null) {
                                        pushVO = iCloudTalkPushCloudIntercomChangeLogDao.getPushRoomInfoByRoomId(rId);
                                        sqlRooms.put(rId,pushVO);
                                    }else{
                                        pushVO = (PushRoomCommanDataVO)sqlRooms.get(rId);
                                        voList.add(pushVO);
                                        continue;
                                    }
                                } catch (Exception e) {
                                    LOG.error("【同一房间开门密码不一致，房间号：】"+rId);
                                    pushVO = null;
                                }
                                if (pushVO != null) {
                                    pushVO.setHardCardNums("");
                                    pushVO.setStatus(pushVO.getStatus().equals("1") ? "1" : "0");
                                    if(pushVO.getStatus().equals("1") &&
                                            StringUtils.isNotBlank(pushVO.getArrearageStatus())&&pushVO.getArrearageStatus().equals("1")){
                                        pushVO.setStatus("2");
                                    }
                                    pushVO=(PushRoomCommanDataVO)StringHandlerUtil.formatString(pushVO);
                                    voList.add(pushVO);
                                }
                            }
                        }
                    }
                    ownedPush.setCommandData(JsonUtil.toJSON(voList));
                    rooms.add(ownedPush);
                }
            }
            if (!rooms.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(rooms);
                this.sendIotMessage(rooms);
            }
        } catch (Exception e) {
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表房间信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+"："+e);
        }
    }


    /**
     * <desc>
     *      处理推送设备响应多媒体信息
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/07
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushMedia(List<DeviceBusinessChangeLogPO> business){
        try {
            List<PushCloudIntercomChangeLogPO> medias = new ArrayList<>();
            Set<String> pro = new HashSet<>();              //已经执行过的项目
            for (DeviceBusinessChangeLogPO bus : business) {
                if (pro.add(bus.getProjectId())) {
                    if (StringUtils.isNotBlank(bus.getCommandParameter())) {
                        //查询项目下所有的云对讲设备
                        List<Map<String, Object>> clouds = iCloudTalkPushCloudIntercomChangeLogDao.getCloudsByProjectId(bus.getProjectId());
                        for (Map<String, Object> cloud : clouds) {
                            PushCloudIntercomChangeLogPO push = new PushCloudIntercomChangeLogPO();
                            push.setCommandType(PushCloudIntercomChangeEnum.PUSH_MEDIA.getType());
                            push.setStatus(0);
                            push.setCreateTime(new Date());
                            push.setCommandId(LogicIdUtil.bussinessId());
                            push.setDeviceUnique(cloud.get("deviceUnique").toString());
                            push.setSn(cloud.get("sn").toString());
                            Map<String, Object> map = new HashMap<>();
                            //文字类型多媒体信息
                            List<Map<String, Object>> texts = new ArrayList<>();
                            //图片类型多媒体信息
                            List<Map<String, Object>> pics = new ArrayList<>();
                            //视频类型多媒体信息
                            List<Map<String, Object>> videos = new ArrayList<>();
                            //查询云对讲的文字多媒体信息
                            if (cloud.get("type").toString().equals(CloudIntercomTypeEnum.GATE.getType().toString())) {
                                //门口机
                                texts = iCloudTalkPushCloudIntercomChangeLogDao.getGates(push.getDeviceUnique(), MediaTypeEnum.TEXT.getType().toString());
                                pics = iCloudTalkPushCloudIntercomChangeLogDao.getGates(push.getDeviceUnique(), MediaTypeEnum.IMGAE.getType().toString());
                                videos = iCloudTalkPushCloudIntercomChangeLogDao.getGates(push.getDeviceUnique(), MediaTypeEnum.VIDEO.getType().toString());
                            } else if (cloud.get("type").toString().equals(CloudIntercomTypeEnum.WALL.getType().toString())) {
                                //围墙机
                                texts = iCloudTalkPushCloudIntercomChangeLogDao.getWalls(push.getDeviceUnique(), MediaTypeEnum.TEXT.getType().toString());
                                pics = iCloudTalkPushCloudIntercomChangeLogDao.getWalls(push.getDeviceUnique(), MediaTypeEnum.IMGAE.getType().toString());
                                videos = iCloudTalkPushCloudIntercomChangeLogDao.getWalls(push.getDeviceUnique(), MediaTypeEnum.VIDEO.getType().toString());
                            }
                            List<PushMediaCommanDataVO> textData = new ArrayList<>();
                            List<PushMediaCommanDataVO> picData = new ArrayList<>();
                            List<PushMediaCommanDataVO> videoData = new ArrayList<>();
                            texts.forEach(text -> {
                                textData.add(this.getMedias(text, MediaTypeEnum.TEXT));
                            });
                            pics.forEach(pic -> {
                                picData.add(this.getMedias(pic, MediaTypeEnum.IMGAE));
                            });
                            videos.forEach(video -> {
                                videoData.add(this.getMedias(video, MediaTypeEnum.VIDEO));
                            });
                            videoData.addAll(textData);
                            videoData.addAll(picData);
                            //云对讲尺寸类型为空或者尺寸类型为7寸时，将资源地址的https改为http
                            if (cloud.get("screenType") == null || ScreenTypeEnum.SEVEN_SCREEN_CLOUD_INTERCOM.getType().equals(cloud.get("screenType").toString())){
                                videoData.forEach(pushMediaCommandDataVO -> {
                                    if (StringUtils.isNotBlank(pushMediaCommandDataVO.getAttacheFileUrl())){
                                        pushMediaCommandDataVO.setAttacheFileUrl(pushMediaCommandDataVO.getAttacheFileUrl().replaceAll("https","http"));
                                    }
                                });
                            }
                            push.setCommandData(JsonUtil.toJSON(videoData));
                            medias.add(push);
                        }
                    }
                }
            }
            if (!medias.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(medias);
                this.sendIotMessage(medias);
            }
        } catch (Exception e) {
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表多媒体信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + "："+e);
        }
    }

    /**
     * <desc>
     *      封装多媒体数据实体
     * </desc>
     *
     * @param data 推送多媒体信息
     * @param typeEnum 多媒体类型枚举类
     * @return
     * @author Jiaqi.X
     * @createDate 2017/12/07
     */
    private  PushMediaCommanDataVO getMedias(Map<String,Object> data,MediaTypeEnum typeEnum){
        PushMediaCommanDataVO vo=new PushMediaCommanDataVO();
        vo.setType(StringHandlerUtil.getNullOrStringForObject(typeEnum.getType()));
        vo.setTitle(StringHandlerUtil.getNullOrStringForObject(data.get("title")));
        vo.setContent(StringHandlerUtil.getNullOrStringForObject(data.get("content")));
        vo.setAttacheFile(StringHandlerUtil.getNullOrStringForObject(data.get("attacheFile")));
        vo.setAttacheFileUrl(StringHandlerUtil.getNullOrStringForObject(data.get("attacheFileUrl")));
        vo.setMd5(StringHandlerUtil.getNullOrStringForObject(data.get("attacheFileMd5")));
        vo.setPutStartTime(StringHandlerUtil.getNullOrStringForObject(data.get("putStartTime")));
        vo.setPutEndTime(StringHandlerUtil.getNullOrStringForObject(data.get("putEndTime")));
        return (PushMediaCommanDataVO)StringHandlerUtil.formatString(vo);
    }

    /**
     * <desc>
     *      处理推送硬件响应设备信息
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/06
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushDevice(List<DeviceBusinessChangeLogPO> business){
        try {
            List<PushCloudIntercomChangeLogPO> devices = new ArrayList<>();
            Map<String, Object> deviceMap = new HashMap<>();
            for (DeviceBusinessChangeLogPO bus : business) {
                List<Map<String, Object>> list =  JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {});
                Set<String> deviceUniques = new HashSet<>();
                list.forEach(deviceUnique -> {
                    deviceUniques.add(deviceUnique.get("deviceUnique").toString());
                });
                for (String deviceUnique : deviceUniques) {
                    Set<String> deviceSet = deviceMap.get(deviceUnique) == null ? new HashSet<>() : (Set<String>) deviceMap.get(deviceUnique);
                    if (deviceSet.add(deviceUnique)) {
                        deviceMap.put(deviceUnique, deviceSet);
                        //判断是否已有相同设备的推送消息
                        PushCloudIntercomChangeLogPO ownedPush = new PushCloudIntercomChangeLogPO();
                        ownedPush.setCommandType(PushCloudIntercomChangeEnum.PUSH_DEVICE.getType());
                        ownedPush.setCommandId(LogicIdUtil.bussinessId());
                        ownedPush.setStatus(0);
                        ownedPush.setCreateTime(new Date());
                        //查询设备详情
                        Map<String, Object> deviceInfo = iCloudTalkPushCloudIntercomChangeLogDao.getPushDeviceInfo(deviceUnique);
                        ownedPush.setDeviceUnique(deviceUnique);
                        ownedPush.setSn(deviceInfo.get("sn").toString());
                        PushDeviceCommanDataVO vo = new PushDeviceCommanDataVO();
                        //需要排除的旧批次号集合
                        List<String> oldBatchNumberArr = new ArrayList<>();
                        //查询出需排除的旧批次集合
                        List<String> oldBatchNumberList = iAppDeviceDao.getOldBatchNumberByProjectId(deviceUnique.substring(0,8));
                        for(String oldBatchNumbers : oldBatchNumberList){
                            for(String oldBatchNumber : oldBatchNumbers.split(",")){
                                oldBatchNumberArr.add(oldBatchNumber);
                            }
                        }
                        //获取项目下最近批次号过期时间
                        String endTimeByProjectId = iAppDeviceDao.getBatchNumberEndTimeByProjectId(deviceUnique.substring(0,8),oldBatchNumberArr.size()>0?oldBatchNumberArr:null);
                        //如果批次号不为空，则查询其对应的过期时间
                        if(deviceInfo.get("batchNumber")!=null && StringUtils.isNotEmpty(deviceInfo.get("batchNumber").toString())){
                            String endTime = iAppDeviceDao.getBatchNumberEndTime(deviceInfo.get("batchNumber").toString());
                            if(StringUtils.isNotEmpty(endTime)){
                                vo.setEndTime(endTime);
                            }else{
                                if(StringUtils.isNotEmpty(endTimeByProjectId)){
                                    vo.setEndTime(endTimeByProjectId);
                                }else{
                                    vo.setEndTime("");
                                }
                            }
                        }else{
                            if(StringUtils.isNotEmpty(endTimeByProjectId)){
                                vo.setEndTime(endTimeByProjectId);
                            }else{
                                vo.setEndTime("");
                            }
                        }
                        vo.setDeviceName(deviceInfo.get("deviceName").toString());
//                        vo.setDeviceQrcodeUrl(deviceInfo.get("qrCode").toString());
                        if(deviceInfo.get("standbyImageUrl")!=null){
                            vo.setStandbyImageUrl(deviceInfo.get("standbyImageUrl").toString());
                        }else{
                            vo.setStandbyImageUrl("");
                        }
                        vo.setDeviceQrcodeUrl("");//二维码固定为空
                        vo.setDeviceStatus(deviceInfo.get("status").toString().equals("1") ? "1" : "0");
                        vo.setEquipMode(StringHandlerUtil.strToIntDef(deviceInfo.get("equipMode").toString(), 1));
                        vo=(PushDeviceCommanDataVO)StringHandlerUtil.formatString(vo);
                        ownedPush.setCommandData(JsonUtil.toJSON(vo));
                        devices.add(ownedPush);
                    }
                }
            }
            if (!devices.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(devices);
                this.sendIotMessage(devices);
            }
        } catch (Exception e) {
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表设备信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ":" + e);
        }
    }

    /**
     * <desc>
     *      处理推送硬件响应用户信息
     * </desc>
     *
     * @param type 1用户项目信息 2用户房间信息
     * @author Jiaqi.X
     * @createDate 2017/12/06
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public synchronized void setPushUser(List<DeviceBusinessChangeLogPO> business, Integer type) {
        try {
            Map<String, Object> addressMap = new HashMap<>();
            List<PushCloudIntercomChangeLogPO> users = new ArrayList<>();
            for(DeviceBusinessChangeLogPO bus : business) {
                if (StringUtils.isNotBlank(bus.getCommandParameter()) && !bus.getCommandParameter().equals("[]")) {
                    //根据type 解析map的结构
                    Map<String, Object> map = new HashMap<>();
                    if (type == 1) {
                        Map<String, Object> projectMap = JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
                        map.put(projectMap.get("userId").toString(), projectMap.get("userId"));
                    } else {
                        List<Map<String, Object>> userRoom = JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {
                        });
                        userRoom.forEach(user->{
                            if (map.get(user.get("userId").toString()) == null) {
                                map.put(user.get("userId").toString(), user.get("userId").toString());
                            }
                        });
                        for (String userId : map.keySet()) {
                            Set<String> roomSet = new HashSet<>();
                            userRoom.forEach(ur -> {
                                if (ur.get("userId").toString().equals(userId)) {
                                    roomSet.add(ur.get("roomId").toString());
                                }
                            });
                            map.put(userId, roomSet.toArray(new String[roomSet.size()]));
                        }
                    }
                    for (String userId : map.keySet()) {
                            //获取项目下有权限的所有云对讲设备信息
                            List<AppCloudIntercomsVO> clouds = iCloudTalkPushCloudIntercomChangeLogDao.getUserClouds(userId, bus.getProjectId());
                            if (clouds == null || clouds.isEmpty()) {
                                continue;
                            }
                            for (AppCloudIntercomsVO cloud : clouds) {
                                List<PushUserCommanDataVO> voList;
                                //判断是否已有相同设备的推送消息
                                PushCloudIntercomChangeLogPO ownedPush;
                                try {
                                    ownedPush = users.stream().filter(roomUser -> roomUser.getDeviceUnique().equals(cloud.getDeviceUnique())).findFirst().get();
                                } catch (NoSuchElementException e) {
                                    ownedPush = null;
                                }
                                //获取用户房间号
                                String[] roomIds;
                                if (type == 1) {
                                    roomIds = StringHandlerUtil.splitString(cloud.getRoomIds());
                                } else {
                                    roomIds = (String[]) map.get(userId);
                                }
                                //如果没有房间
                                if (roomIds.length < 1) {
                                    continue;
                                }
                                if (ownedPush != null) {
                                    voList = (List<PushUserCommanDataVO>) JsonUtil.toListObject(ownedPush.getCommandData(), ArrayList.class, PushUserCommanDataVO.class);
                                } else {
                                    ownedPush = new PushCloudIntercomChangeLogPO();
                                    ownedPush.setCommandId(LogicIdUtil.bussinessId());
                                    ownedPush.setDeviceUnique(cloud.getDeviceUnique());
                                    ownedPush.setCreateTime(new Date());
                                    ownedPush.setStatus(0);
                                    ownedPush.setCommandType(PushCloudIntercomChangeEnum.PUSH_USER.getType());
                                    //获取设备sn
                                    ownedPush.setSn(iCloudTalkPushCloudIntercomChangeLogDao.getSnByDeviceUnique(cloud.getDeviceUnique()));
                                    users.add(ownedPush);
                                    voList = new ArrayList<>();
                                }
                            if (roomIds.length > 0) {
                                for (String roomId : roomIds) {
                                    //判断在需要更新的设备中是否有相同的用户房间信息
                                    Optional<PushUserCommanDataVO> optUser = voList.stream().filter(pu -> pu.getUserId().equals(userId) && pu.getRoomId().equals(roomId)).findFirst();
                                    if (!optUser.isPresent()) {
                                        PushUserCommanDataVO pushUser = new PushUserCommanDataVO();
                                        pushUser.setUserId(userId);
                                        pushUser.setRoomId(roomId);
                                        if (!(iAppDeviceDao.checkDeviceInRoom(cloud.getDeviceUnique(), roomId) > 0)) {
                                            continue;
                                        } else {
                                            //查询用户的项目信息
                                            Map<String, Object> projectInfo = null;
                                            try {
                                                projectInfo = iCloudTalkPushCloudIntercomChangeLogDao.getPushUserProjectInfo(pushUser.getUserId(), bus.getProjectId(), pushUser.getRoomId());
                                                if (projectInfo == null) {
                                                    continue;
                                                }
                                            } catch (Exception e) {
                                                LOG.error(String.format("【同步业务指令至响应硬件结果表用户信息执行失败：用户与项目信息有多条】 用户Id:%s 项目id:%s", pushUser.getUserId(), bus.getProjectId()));
                                                continue;
                                            }
                                            pushUser.setQqNum(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("qqNum")));
                                            pushUser.setTinyId(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("tinyId")));
                                            pushUser.setIsOnline("1");
                                            pushUser.setIsAllowApp(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("isAllowApp")));
                                            pushUser.setSipAccount(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("sipAccount")));
                                            pushUser.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("idcardKey")));
                                            pushUser.setIsLoss(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("isLoss")));
                                            pushUser.setFacePicUrl(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("imageUrl")));
                                            pushUser.setStartTime(null);
                                            pushUser.setEndTime(null);
                                            //组装用户信息vip标识符
                                            if (projectInfo.get("userLabel")==null){
                                                pushUser.setIsVip(0);
                                            }else {
                                                pushUser.setIsVip(Arrays.asList(projectInfo.get("userLabel").toString().split(",")).contains("1")?1:0);
                                            }

                                            //组装常用楼层和公共楼层
                                            //1.得到用户所拥有的楼层机号对应关系
                                            String commonFloor = StringHandlerUtil.getNullOrStringForObject(projectInfo.get("commonFloor"));
                                            String publicFloor = StringHandlerUtil.getNullOrStringForObject(projectInfo.get("publicFloor"));
                                            //2.获取当前云对讲的地址
                                            Map<String, Object> address = iCloudIntercomDeviceServiceDao.getAddressByDeviceUnique(cloud.getDeviceUnique());

                                            addressMap.put("unitId",address.get("unitIds"));

                                            //3.获取当前地址的下的电梯 正背们和机号
                                            List<CloudElevatorVO> DeviceUniques = iPropertyEquipDao.getElevatorListByAddress(addressMap);
                                            //4.比对用户所用的常用楼层的对应的机号的楼层号

                                            Map jsonCommonFloor=null;
                                            Map jsonPublicFloor=null;
                                            if (commonFloor!=null){
                                                jsonCommonFloor = JSON.parseObject(commonFloor, HashMap.class);
                                            }
                                            if (publicFloor!=null){
                                                jsonPublicFloor =  JSON.parseObject(publicFloor, HashMap.class);
                                            }

                                            for (CloudElevatorVO cloudElevatorVO : DeviceUniques) {
                                                Map<String, Object> elevator = iCloudTalkPushCloudIntercomChangeLogDao.getElevatorByDeviceUnique(cloudElevatorVO.getDeviceUnique());
                                                if (commonFloor==null){
                                                    if ("1".equals(elevator==null?null:elevator.get("liftDoorType")+"")){
                                                        //正门常用楼层
                                                        pushUser.setFrontCommonFloor("");
                                                    }else {
                                                        pushUser.setBackCommonFloor("");
                                                    }
                                                }else {
                                                    if (jsonCommonFloor.containsKey(cloudElevatorVO.getDeviceUnique())){
                                                        if ("1".equals(elevator==null?null:elevator.get("liftDoorType")+"")){
                                                            //正门常用楼层
                                                            pushUser.setFrontCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                        }else {
                                                            pushUser.setBackCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                        }
                                                    }
                                                }
                                                if (publicFloor==null){
                                                    if ("1".equals(elevator==null?null:elevator.get("liftDoorType")+"")){
                                                        //正门常用楼层
                                                        pushUser.setFrontPublicFloor("");
                                                    }else {
                                                        pushUser.setBackPublicFloor("");
                                                    }
                                                }else {
                                                    if (jsonPublicFloor.containsKey(cloudElevatorVO.getDeviceUnique())){
                                                        if ("1".equals(elevator==null?null:elevator.get("liftDoorType")+"")){
                                                            //正门常用楼层
                                                            pushUser.setFrontPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                        }else {
                                                            pushUser.setBackPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                        }
                                                    }
                                                }

                                            }

                                            //5.组装正背门楼层信息


                                            String userRoomStatus = projectInfo.get("userRoomStatus").toString();
                                            String userProjectStatus = projectInfo.get("userProjectStatus").toString();
                                            String projectStatus = projectInfo.get("projectStatus").toString();
                                            String status = projectInfo.get("status").toString();
                                            if (userRoomStatus.equals("2") && userProjectStatus.equals("1") && status.equals("1") && projectStatus.equals("1")) {
                                                pushUser.setStatus("1");
                                            } else {
                                                pushUser.setStatus("0");
                                            }



                                            pushUser.setUserName(StringHandlerUtil.getNullOrStringForObject(projectInfo.get("userName")));
                                            pushUser.setHouseUserType(projectInfo.get("houserType") != null ? Integer.valueOf(projectInfo.get("houserType").toString()) : null);
                                            pushUser = (PushUserCommanDataVO) StringHandlerUtil.formatString(pushUser);
                                            voList.add(pushUser);
                                        }
                                    }
                                }
                            }
                            ownedPush.setCommandData(JsonUtil.toJSON(voList));
                        }
                    }
                    for (String userId : map.keySet()) {
                        //访客的时候
                        //获取访客信息 以及 房间下的云对讲设备
                        List<PushCloudVisitorInfoDeviceVO> list = iCloudTalkPushCloudIntercomChangeLogDao.getVisitorDeviceInfo(userId);
                        for (PushCloudVisitorInfoDeviceVO vo : list) {
                            List<PushUserCommanDataVO> voList = new ArrayList<>();
                            PushCloudIntercomChangeLogPO ownedPush = new PushCloudIntercomChangeLogPO();
                            ownedPush.setCommandId(LogicIdUtil.bussinessId());
                            ownedPush.setDeviceUnique(vo.getDeviceUnique());
                            ownedPush.setSn(vo.getSn());
                            ownedPush.setCreateTime(new Date());
                            ownedPush.setStatus(0);
                            ownedPush.setCommandType(PushCloudIntercomChangeEnum.PUSH_USER.getType());
                            ownedPush.setSn(vo.getSn());

                            PushUserCommanDataVO pushUser = new PushUserCommanDataVO();
                            pushUser.setUserId(vo.getVFaceId());
                            pushUser.setStartTime(vo.getStartTime());
                            pushUser.setEndTime(vo.getEndTime());
                            pushUser.setHouseUserType(0);
                            pushUser.setRoomId(vo.getRoomId());
                            pushUser.setUserName("");
                            pushUser.setHouseUserType(0);
                            pushUser.setQqNum("");
                            pushUser.setTinyId("");
                            pushUser.setIsOnline("");
                            pushUser.setIsAllowApp("");
                            pushUser.setSipAccount("");
                            pushUser.setIdcardKey(vo.getIdcardKey());
                            pushUser.setIsLoss("");
                            pushUser.setFacePicUrl(vo.getFacePicUrl() == null?vo.getPassId():vo.getFacePicUrl());
                            pushUser.setStatus(vo.getStatus());
                            //访客为普通的vip标识
                            pushUser.setIsVip(0);

                            voList.add(pushUser);
                            ownedPush.setCommandData(JsonUtil.toJSON(voList));
                            users.add(ownedPush);
                        }
                    }
                }
            }
            //去除推送空消息的设备
            for (int i = users.size() - 1; i >= 0; i--) {
                if (users.get(i).getCommandData().equals("[]")) {
                    users.remove(i);
                }
            }
            if (!users.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(users);
                this.sendIotMessage(users);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表用户信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ":" +e);
        }
    }



    /**
     * <desc>
     *      处理推送硬件响应项目信息
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/05
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushProject(List<DeviceBusinessChangeLogPO> business) {
        try {
            Set<String> pro = new HashSet<>();
            List<PushCloudIntercomChangeLogPO> projects=new ArrayList<>();
            for (DeviceBusinessChangeLogPO bus : business) {
                if (pro.add(bus.getProjectId())) {
                    List<DeviceCloudIntercomInfoPO> clouds = iDeviceCloudIntercomInfoDao.getCloudIntercomsByProjectId(bus.getProjectId());
                    PushProjectCommanDataVO vo = iCloudTalkPushCloudIntercomChangeLogDao.getProjectById(business.get(0).getProjectId());
                    List<CloudIntercomDeviceVO.PropertyValue> list = iCloudIntercomDeviceServiceDao.getPropertyInfo(bus.getProjectId(),1);
                    if (list.size() == 0) {
                        list = new ArrayList<>();
                        list.add(new CloudIntercomDeviceVO.PropertyValue());
                    }
                    vo.setDeploys(list);
                    vo.setH5PaymentHtml(H5_PAYMENT_HTML);
                    //deviceEndTime为空是为兼容已出货的第一版云服务费的设备
                    vo.setDeviceEndTime("");
                    for (DeviceCloudIntercomInfoPO cloud : clouds) {
                        //查询项目信息
                        PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                        po.setCommandType(PushCloudIntercomChangeEnum.PUSH_PROJECT.getType());
                        po.setCommandId(LogicIdUtil.bussinessId());
                        po.setCommandData(JsonUtil.toJSON(vo));
                        po.setDeviceUnique(cloud.getDeviceUnique());
                        po.setSn(cloud.getSn());
                        po.setStatus(0);
                        po.setCreateTime(new Date());
                        po=(PushCloudIntercomChangeLogPO)StringHandlerUtil.formatString(po);
                        projects.add(po);
                    }
                }
                break;
            }
            if (!projects.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(projects);
                this.sendIotMessage(projects);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表项目信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+":"+e);
        }
    }

    /**
     * <desc>
     *      处理推送人脸库变更信息
     * </desc>
     *
     * @author Qiang.S
     * @createDate 2018/05/25
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushFaceInfo(List<DeviceBusinessChangeLogPO> business) {
        try {
            List<PushCloudIntercomChangeLogPO> projects=new ArrayList<>();
            for (DeviceBusinessChangeLogPO bus : business) {
                List<DeviceCloudIntercomInfoPO> clouds = iDeviceCloudIntercomInfoDao.getCloudIntercomsByProjectId(bus.getProjectId());
                PushFaceInfoCommanDataVO vo = iCloudTalkPushCloudIntercomChangeLogDao.getFaceInfoById(business.get(0).getProjectId());
                //处理推送信息
                if (vo == null) {
                    vo = new PushFaceInfoCommanDataVO();
                    vo.setLivenessControl("");
                    vo.setQualityControl("");
                    vo.setGroupId("");
                    vo.setApiKey("");
                    vo.setAppId("");
                    vo.setSecretKey("");
                    vo.setScore(0);
                }else {
                    vo.setEnable(true);
                    if ("0".equals(vo.getLivenessControl())) {vo.setLivenessControl("LOW");}
                    if ("1".equals(vo.getLivenessControl())) {vo.setLivenessControl("NORMAL");}
                    if ("2".equals(vo.getLivenessControl())) {vo.setLivenessControl("HIGH");}
                    if ("3".equals(vo.getLivenessControl())) {vo.setLivenessControl("NONE");}
                }
                for (DeviceCloudIntercomInfoPO cloud : clouds) {
                    //查询项目信息
                    PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                    po.setCommandType(PushCloudIntercomChangeEnum.PUSH_FACE.getType());
                    po.setCommandId(LogicIdUtil.bussinessId());
                    JSONObject json = new JSONObject();
                    json.put("face",vo);
                    po.setCommandData(json.toString());
                    po.setDeviceUnique(cloud.getDeviceUnique());
                    po.setSn(cloud.getSn());
                    po.setStatus(0);
                    po.setCreateTime(new Date());
                    po=(PushCloudIntercomChangeLogPO)StringHandlerUtil.formatString(po);
                    projects.add(po);
                }
            }
            if (!projects.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(projects);
                this.sendIotMessage(projects);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步人脸库信息指令至响应硬件执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+":"+e);
        }
    }

    /**
     * <desc>
     *      处理推送单个设备人脸信息配置变更
     * </desc>
     *
     * @author JuGuang.S
     * @createDate 2018/07/03
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushDeviceFaceInfo(List<DeviceBusinessChangeLogPO> business) {
        try {
            List<PushCloudIntercomChangeLogPO> projects=new ArrayList<>();
            for (DeviceBusinessChangeLogPO bus : business) {
                List<Map<String, Object>> list =  JsonUtil.decode(bus.getCommandParameter(), new TypeReference<List<Map<String, Object>>>() {});
                DeviceCloudIntercomInfoPO cloud = iDeviceCloudIntercomInfoDao.getByDeviceUnique(list.get(0).get("deviceUnique").toString(),null);
                PushFaceInfoCommanDataVO vo = iCloudTalkPushCloudIntercomChangeLogDao.getFaceInfoById(business.get(0).getProjectId());
                DeviceCloudIntercomInfoPO infoPO = iDeviceCloudIntercomInfoDao.getByDeviceUniqueAndIsFaceRecognition(list.get(0).get("deviceUnique").toString());
                //处理推送信息
                if (infoPO == null) {
                    vo = new PushFaceInfoCommanDataVO();
                    vo.setLivenessControl("");
                    vo.setQualityControl("");
                    vo.setGroupId("");
                    vo.setApiKey("");
                    vo.setAppId("");
                    vo.setSecretKey("");
                    vo.setScore(0);
                }else {
                    vo.setEnable(true);
                    if ("0".equals(vo.getLivenessControl())) {vo.setLivenessControl("LOW");}
                    if ("1".equals(vo.getLivenessControl())) {vo.setLivenessControl("NORMAL");}
                    if ("2".equals(vo.getLivenessControl())) {vo.setLivenessControl("HIGH");}
                    if ("3".equals(vo.getLivenessControl())) {vo.setLivenessControl("NONE");}
                }

                PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                po.setCommandType(PushCloudIntercomChangeEnum.PUSH_FACE.getType());
                po.setCommandId(LogicIdUtil.bussinessId());
                JSONObject json = new JSONObject();
                json.put("face",vo);
                po.setCommandData(json.toString());
                po.setDeviceUnique(cloud.getDeviceUnique());
                po.setSn(cloud.getSn());
                po.setStatus(0);
                po.setCreateTime(new Date());
                po=(PushCloudIntercomChangeLogPO)StringHandlerUtil.formatString(po);
                projects.add(po);
            }
            if (!projects.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(projects);
                this.sendIotMessage(projects);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步单个设备人脸信息配置变更指令至响应硬件执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+":"+e);
        }
    }


    /**
     * <desc>
     *      处理推送硬件临时权限信息
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2017/12/05
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void setPushTemp(List<DeviceBusinessChangeLogPO> business) {
        try {
            List<PushCloudIntercomChangeLogPO> projects=new ArrayList<>();
            for (DeviceBusinessChangeLogPO bus : business) {
                Map<String,Object> map = JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
                String oldTalkAuth = StringHandlerUtil.getNullOrStringForObject(map.get("talkAuth"));
                String[] oldTalkAuthDeviceIds = StringHandlerUtil.splitString(oldTalkAuth);
                List<String> oldTalkAuthList = Arrays.asList(oldTalkAuthDeviceIds);
                Integer type = Integer.valueOf(map.get("type").toString());
                if(type == 1) {
                    //获取云对讲
                    List<String> addressDeviceIds = new ArrayList<>();
                    List<Map<String, Object>> auths = iCloudIntercomDeviceServiceDao.getPushTempAuths(map.get("projectId").toString(), map.get("userId").toString());
                    int delete = 0;
                    if(auths.isEmpty()){
                        if(map.get("talkAuthList")!=null) {
                            List<Map<String,Object>> talkAuthList = JsonUtil.decode(map.get("talkAuthList").toString(), new TypeReference<List<Map<String, Object>>>() {});
                            if(!talkAuthList.isEmpty()) {
                                delete = 1;
                                auths.add(talkAuthList.get(0));
                            }
                        }
                    }else{
                        //清除迁出地址下的设备
                        if(map.get("talkAuthList")!=null) {
                            AppEntranceOrCloudIntercomAuthVO doorVO = StringHandlerUtil.converEntranceOrCloudIntercomAuth(PropertyEquipTypeEnum.ENTRANCE.getType(),
                                    JsonUtil.decode(map.get("talkAuthList").toString(), new TypeReference<List<Map<String, Object>>>() {
                                    }));
                            if(doorVO!=null){
                                addressDeviceIds = doorVO.getDeviceIds();
                            }
                        }
                    }
                    for (Map<String, Object> auth : auths) {
                        List<Map<String, Object>> cloudAuth = iAppDeviceDao.getCloudIntercomsAuth(auth.get("userId").toString(), map.get("projectId").toString());
                        AppEntranceOrCloudIntercomAuthVO cloudVO;
                        if(delete == 0) {
                           cloudVO = StringHandlerUtil.converEntranceOrCloudIntercomAuth(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType(), cloudAuth);
                        }else{
                            cloudVO = StringHandlerUtil.converEntranceOrCloudIntercomAuth(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType(),
                                    JsonUtil.decode(map.get("talkAuthList").toString(), new TypeReference<List<Map<String, Object>>>() {}));
                        }
                        for (String deviceId : cloudVO.getDeviceIds()) {
                            EntranceTempAuthVO tempVO = new EntranceTempAuthVO();
                            tempVO.setUserId(StringHandlerUtil.getNullOrStringForObject(auth.get("userId")));
                            tempVO.setUserName(StringHandlerUtil.getNullOrStringForObject(auth.get("userName")));
                            tempVO.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(auth.get("idcardKey")));
                            tempVO.setVisitorType(auth.get("visitorType") != null ? Integer.valueOf(auth.get("visitorType").toString()) : null);
                            tempVO.setIsLoss(StringHandlerUtil.getNullOrStringForObject(auth.get("isLoss")));
                            //查询门禁地址
                            Map<String, Object> address = iCloudIntercomDeviceServiceDao.getDeviceAddress(map.get("projectId").toString() + "3" + deviceId);
                            //获取门禁地址下的电梯
                            List<CloudElevatorVO> elevators = new ArrayList<>();
                            if(address != null) {
                                elevators = iCloudElevatorDao.getDeviceUniquesByEntranceAddress(address);
                            }
                            //获取地址下电梯的临时权限
                            Set<String> frontFloor = new HashSet<>();           //正门楼层
                            Set<String> backFloor = new HashSet<>();            //背门楼层
                            if(delete == 0) {
                                for (CloudElevatorVO elevator : elevators) {
                                    //获取电梯的授权设备信息
                                    List<AppElevatorAuthDTO> elevatorAuths = iCloudElevatorDao.getFloorAuth(auth.get("userId").toString(),
                                            map.get("projectId").toString(), Integer.valueOf(elevator.getDeviceId()));
                                    AppElevatorAuthVO tempElevatorAuth = StringHandlerUtil.convertElevatorAuth(elevatorAuths);
                                    Optional<AppElevatorInfoVO> eAuth = tempElevatorAuth.getElevatorAuth().stream().filter(temp -> temp.getDeviceId().equals(elevator.getDeviceId())).findFirst();
                                    if (eAuth.isPresent()) {
                                        String[] floors = StringHandlerUtil.splitString(eAuth.get().getLiveFloor());
                                        if (floors.length > 0) {
                                            String floorsStr = iCloudElevatorDao.getFloorNumByNaturalFloor(floors, map.get("projectId").toString() + "1" + eAuth.get().getDeviceId());
                                            floors = StringHandlerUtil.splitString(floorsStr);
                                        }
                                        for (String floor : floors) {
                                            if (elevator.getLiftDoorType() == 1) {
                                                frontFloor.add(floor);
                                            } else {
                                                backFloor.add(floor);
                                            }
                                        }
                                        tempVO.setFrontFloor(String.join(",", frontFloor));
                                        tempVO.setBackFloor(String.join(",", backFloor));
                                        if (StringUtils.isNotBlank(tempVO.getFrontFloor())) {
                                            tempVO.setFrontFloor(iCloudElevatorDao.getFloorNumByNaturalFloor(StringHandlerUtil.splitString(tempVO.getFrontFloor()), map.get("projectId").toString() + "1" + elevator.getDeviceId()));
                                        }
                                        if (StringUtils.isNotBlank(tempVO.getBackFloor())) {
                                            tempVO.setBackFloor(iCloudElevatorDao.getFloorNumByNaturalFloor(StringHandlerUtil.splitString(tempVO.getBackFloor()), map.get("projectId").toString() + "1" + elevator.getDeviceId()));
                                        }
                                    }
                                }
                                tempVO.setStatus(auth.get("status").toString());
                            }else{
                                tempVO.setStatus("0");
                            }
                            if(!oldTalkAuthList.isEmpty() && !oldTalkAuthList.stream().filter(d->d.equals(deviceId)).findFirst().isPresent()){
                                tempVO.setStatus("0");
                            }
                            if(!addressDeviceIds.isEmpty() && !addressDeviceIds.stream().filter(d->d.equals(deviceId)).findFirst().isPresent()){
                                tempVO.setStatus("0");
                            }
                            tempVO = (EntranceTempAuthVO)StringHandlerUtil.formatString(tempVO);
                            List<EntranceTempAuthVO> list = new ArrayList<>();
                            list.add(tempVO);
                            PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                            po.setCommandType(PushCloudIntercomChangeEnum.PUSH_TEMP.getType());
                            po.setCommandId(LogicIdUtil.bussinessId());
                            Map<String,Object> result = new HashMap<>();
                            result.put("deviceAuthArr",list);
                            po.setCommandData(JsonUtil.toJSON(result));
                            po.setDeviceUnique(map.get("projectId").toString() + "3" + deviceId);
                            po.setSn(iDeviceCloudIntercomInfoDao.getSnByDeviceUnique(po.getDeviceUnique()));
                            po.setStatus(0);
                            po.setCreateTime(new Date());
                            po = (PushCloudIntercomChangeLogPO) StringHandlerUtil.formatString(po);
                            projects.add(po);
                        }
                    }
//                    //迁出的地址权限
                    if(!addressDeviceIds.isEmpty()){
                        for(String deviceId : addressDeviceIds){
                            Map<String,Object> userInfo = iCloudElevatorDao.getPushTempUserInfo(map.get("projectId").toString(),map.get("userId").toString());
                            EntranceTempAuthVO tempVO = new EntranceTempAuthVO();
                            tempVO.setUserId(StringHandlerUtil.getNullOrStringForObject(userInfo.get("userId")));
                            tempVO.setUserName(StringHandlerUtil.getNullOrStringForObject(userInfo.get("userName")));
                            tempVO.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(userInfo.get("idcardKey")));
                            tempVO.setVisitorType(userInfo.get("visitorType") != null ? Integer.valueOf(userInfo.get("visitorType").toString()) : null);
                            tempVO.setIsLoss(StringHandlerUtil.getNullOrStringForObject(userInfo.get("isLoss")));
                            tempVO.setStatus("0");
                            tempVO = (EntranceTempAuthVO)StringHandlerUtil.formatString(tempVO);
                            List<EntranceTempAuthVO> list = new ArrayList<>();
                            list.add(tempVO);
                            PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                            po.setCommandType(PushCloudIntercomChangeEnum.PUSH_TEMP.getType());
                            po.setCommandId(LogicIdUtil.bussinessId());
                            Map<String,Object> result = new HashMap<>();
                            result.put("deviceAuthArr",list);
                            po.setCommandData(JsonUtil.toJSON(result));
                            po.setDeviceUnique(map.get("projectId").toString() + "3" + deviceId);
                            po.setSn(iDeviceCloudIntercomInfoDao.getSnByDeviceUnique(po.getDeviceUnique()));
                            po.setStatus(0);
                            po.setCreateTime(new Date());
                            po = (PushCloudIntercomChangeLogPO) StringHandlerUtil.formatString(po);
                            projects.add(po);
                        }
                    }
//                    //取消的临时权限
                    if(oldTalkAuthList.isEmpty()){
                        for(String deviceId : oldTalkAuthDeviceIds){
                            Map<String,Object> userInfo = iCloudElevatorDao.getPushTempUserInfo(map.get("projectId").toString(),map.get("userId").toString());
                            EntranceTempAuthVO tempVO = new EntranceTempAuthVO();
                            tempVO.setUserId(StringHandlerUtil.getNullOrStringForObject(userInfo.get("userId")));
                            tempVO.setUserName(StringHandlerUtil.getNullOrStringForObject(userInfo.get("userName")));
                            tempVO.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(userInfo.get("idcardKey")));
                            tempVO.setVisitorType(userInfo.get("visitorType") != null ? Integer.valueOf(userInfo.get("visitorType").toString()) : null);
                            tempVO.setIsLoss(StringHandlerUtil.getNullOrStringForObject(userInfo.get("isLoss")));
                            tempVO.setStatus("0");
                            tempVO = (EntranceTempAuthVO)StringHandlerUtil.formatString(tempVO);
                            List<EntranceTempAuthVO> list = new ArrayList<>();
                            list.add(tempVO);
                            PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                            po.setCommandType(PushCloudIntercomChangeEnum.PUSH_TEMP.getType());
                            po.setCommandId(LogicIdUtil.bussinessId());
                            Map<String,Object> result = new HashMap<>();
                            result.put("deviceAuthArr",list);
                            po.setCommandData(JsonUtil.toJSON(result));
                            po.setDeviceUnique(map.get("projectId").toString() + "3" + deviceId);
                            po.setSn(iDeviceCloudIntercomInfoDao.getSnByDeviceUnique(po.getDeviceUnique()));
                            po.setStatus(0);
                            po.setCreateTime(new Date());
                            po = (PushCloudIntercomChangeLogPO) StringHandlerUtil.formatString(po);
                            projects.add(po);
                        }
                    }
                }else{
                    //获取访客
                    DeviceTempVisitorVO visitor = iDeviceEntranceInfoDao.getVisitorsByVisitorId(map.get("userId").toString());
                    Set<String> deviceUniques = new HashSet<>();
                    if (StringUtils.isNotBlank(visitor.getOwnerAuthDeviceUnique())){
                        for(String deviceUnique:StringHandlerUtil.splitString(visitor.getOwnerAuthDeviceUnique())){
                            if(deviceUnique.substring(8,9).equals("3")){
                                deviceUniques.add(deviceUnique);
                            }
                        }
                    }
                    for(String deviceUnique : deviceUniques){
                        EntranceTempAuthVO tempVO = new EntranceTempAuthVO();
                        BeanUtils.copyProperties(visitor, tempVO);
                        //查询门禁地址
                        Map<String, Object> address = iCloudIntercomDeviceServiceDao.getDeviceAddress(deviceUnique);
                        //获取门禁地址下的电梯
                        List<CloudElevatorVO> elevators = iCloudElevatorDao.getDeviceUniquesByEntranceAddress(address);
                        if (StringUtils.isNotBlank(visitor.getFrontElevatorAuth())) {
                            Map<String, Object> frontList = JsonUtil.toObject(visitor.getFrontElevatorAuth(), HashMap.class);
                            Set<String> fronts = new HashSet<>();
                            for (String key : frontList.keySet()) {
                                Optional<CloudElevatorVO> optional = elevators.stream().filter(elevator -> elevator.getDeviceId().equals(key)).findFirst();
                                if (optional.isPresent()) {
                                    String[] floor = StringHandlerUtil.splitString(frontList.get(key).toString());
                                    if(floor.length > 0){
                                        String floors = iCloudElevatorDao.getFloorNumByNaturalFloor(floor,optional.get().getProjectId() + "1" + optional.get().getDeviceId());
                                        floor = StringHandlerUtil.splitString(floors);
                                    }
                                    for (String f : floor) {
                                        fronts.add(f);
                                    }
                                }
                            }
                            tempVO.setFrontFloor(String.join(",", fronts));
                        }
                        if (StringUtils.isNotBlank(visitor.getBackElevatorAuth())) {
                            Map<String, Object> backList = JsonUtil.toObject(visitor.getBackElevatorAuth(), HashMap.class);
                            Set<String> backs = new HashSet<>();
                            for (String key : backList.keySet()) {
                                Optional<CloudElevatorVO> optional = elevators.stream().filter(elevator -> elevator.getDeviceId().equals(key)).findFirst();
                                if (optional.isPresent()) {
                                    String[] floor = StringHandlerUtil.splitString(backList.get(key).toString());
                                    if(floor.length > 0){
                                        String floors = iCloudElevatorDao.getFloorNumByNaturalFloor(floor,optional.get().getProjectId() + "1" + optional.get().getDeviceId());
                                        floor = StringHandlerUtil.splitString(floors);
                                    }
                                    for (String f : floor) {
                                        backs.add(f);
                                    }
                                }
                            }
                            tempVO.setBackFloor(String.join(",", backs));
                        }
                        tempVO = (EntranceTempAuthVO)StringHandlerUtil.formatString(tempVO);
                        List<EntranceTempAuthVO> list = new ArrayList<>();
                        list.add(tempVO);
                        PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                        po.setCommandType(PushCloudIntercomChangeEnum.PUSH_TEMP.getType());
                        po.setCommandId(LogicIdUtil.bussinessId());
                        Map<String,Object> result = new HashMap<>();
                        result.put("deviceAuthArr",list);
                        po.setCommandData(JsonUtil.toJSON(result));
                        po.setDeviceUnique(deviceUnique);
                        po.setSn(iDeviceCloudIntercomInfoDao.getSnByDeviceUnique(po.getDeviceUnique()));
                        po.setStatus(0);
                        po.setCreateTime(new Date());
                        po = (PushCloudIntercomChangeLogPO) StringHandlerUtil.formatString(po);
                        projects.add(po);
                    }
                }
            }
            if (!projects.isEmpty()) {
                iCloudTalkPushCloudIntercomChangeLogDao.batchSave(projects);
                this.sendIotMessage(projects);
            }
        }catch (Exception e){
            throw new DataAccessException("【定时任务】同步业务指令至响应硬件结果表临时权限信息执行失败，当前时间】:" +
                    DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")+":"+e);
        }
    }

    /**
     * <desc>
     * 根据设备唯一标识符查询电梯正背门信息
     * </desc>
     *
     * @param deviceUnique
     * @Author chengshican
     * @Date \ 15:21
     * @Param
     * @Return
     * @Exception
     */
    @Override
    public Map<String, Object> getElevatorByDeviceUnique(String deviceUnique) {
        return iCloudTalkPushCloudIntercomChangeLogDao.getElevatorByDeviceUnique(deviceUnique);
    }

    /**
     * <desc>
     *      黑名单信息变更
     * </desc>
     *
     * @param business
     * @author Jiaqi.X
     * @createDate 2019/10/15
     */
    public void setBlackList(List<DeviceBusinessChangeLogPO> business) throws IOException {
        List<PushCloudIntercomChangeLogPO> pushBlackList = new ArrayList<>();
        for (DeviceBusinessChangeLogPO bus : business) {
            Map<String, Object> roomMap = JsonUtil.toObject(bus.getCommandParameter(), HashMap.class);
            String roomId = roomMap.get("roomId").toString();
            String projectId = roomMap.get("projectId").toString();
            //获取房间下的云对讲
            Map<String,Object> address = iPropertyEquipDao.getAddressByRoomId(roomId);
            List<DeviceCloudIntercomInfoPO> talkList = iPropertyEquipDao.getTalkListByAddress(address);
            for(DeviceCloudIntercomInfoPO talk : talkList){
                List<BlackListVO> blackList = new ArrayList<>();
                Set<String> userIds = new HashSet<>();
                //地址用户
                List<UserBlackInfoVO> users = iCloudIntercomDeviceServiceDao.getUserBlackInfosByRoomId(roomId,projectId);
                for (UserBlackInfoVO user : users) {
                    if(userIds.add(user.getUid()+user.getRoomNo())) {
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(StringHandlerUtil.autlSupply(8, user.getUid(), "0"));
                        blackListVO.setType(1);
                        if ((user.getChargeMode()!=null && user.getChargeMode() == 1) && (user.getUsableCount() == null || user.getUsableCount() <= 0)) {
                            blackListVO.setStatus(1);
                        } else {
                            blackListVO.setStatus(0);
                        }
                        blackListVO.setBatch(Integer.valueOf(user.getBatch()));
                        blackListVO.setRoomNo(StringHandlerUtil.autlSupply(2, Integer.toHexString(Integer.valueOf(user.getRoomNo())), "0").toUpperCase());
                        blackList.add(blackListVO);
                    }
                }
                //临时权限黑名单
                List<UserBlackInfoVO> tempUsers = iCloudIntercomDeviceServiceDao.getTempBlackInfosByRoomId(roomId,projectId,
                        Integer.valueOf(StringHandlerUtil.getDeviceIdByDeviceUnique(talk.getDeviceUnique())));
                tempUsers.stream().forEach(user->{
                    if(userIds.add(user.getUid()+user.getRoomNo())) {
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(StringHandlerUtil.autlSupply(8, user.getUid(), "0"));
                        blackListVO.setType(1);
                        if ((user.getChargeMode()!=null && user.getChargeMode() == 1) && (user.getUsableCount() == null || user.getUsableCount() <= 0)) {
                            blackListVO.setStatus(1);
                        }else{
                            blackListVO.setStatus(0);
                        }
                        blackListVO.setBatch(Integer.valueOf(user.getBatch()));
                        blackListVO.setRoomNo(StringHandlerUtil.autlSupply(2, Integer.toHexString(Integer.valueOf(user.getRoomNo())), "0").toUpperCase());
                        blackList.add(blackListVO);
                    }
                });
                if(!blackList.isEmpty()) {
                    PushCloudIntercomChangeLogPO po = new PushCloudIntercomChangeLogPO();
                    po.setCommandType(PushCloudIntercomChangeEnum.PUSH_BLACK.getType());
                    po.setCommandId(LogicIdUtil.bussinessId());
                    po.setCommandData(JsonUtil.toJSON(blackList));
                    po.setDeviceUnique(talk.getDeviceUnique());
                    po.setSn(talk.getSn());
                    po.setStatus(0);
                    po.setCreateTime(new Date());
                    po = (PushCloudIntercomChangeLogPO) StringHandlerUtil.formatString(po);
                    pushBlackList.add(po);
                }
            }
        }
        if (!pushBlackList.isEmpty()) {
            iCloudTalkPushCloudIntercomChangeLogDao.batchSave(pushBlackList);
            this.sendIotMessage(pushBlackList);
        }
    }

    /**
     * <desc>
     *      处理推送设备指令转换为iot指令
     * </desc>
     *
     * @param list 指令内容
     * @author Qiang.S
     * @createDate 2019/07/05
     */
    private void sendIotMessage (List<PushCloudIntercomChangeLogPO> list) {
        try {
            //过滤离线设备
            for (int i = list.size() - 1; i >= 0; i--) {
                if (StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY + list.get(i).getDeviceUnique()))
                        || !"2".equals(redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY + list.get(i).getDeviceUnique()))) {
                    list.remove(i);
                }
            }
            if (list.size() > 0) {
                //取得版本和iotkey
                ProductTypePO productKey = iCloudTalkPushCloudIntercomChangeLogDao.getIntercomVersonIotkey(list.get(0).getDeviceUnique());
                //iot指令准备
                for (PushCloudIntercomChangeLogPO po : list) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),po.getDeviceUnique(),"itlong","2001",1,po.getCommandType().toString(),1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
